<template>
  <div style="max-height: 50vh;overflow: auto">
    <el-form label-width="80px" :model="sendForm" :rules="sendRules" ref="sendRef">
      <div style="display: flex;">
        <!-- <el-form-item label="发货仓库" prop="shopName">
          <el-select v-model="sendForm.shopName" filterable placeholder="请选择" @change="selectShop">
            <el-option
              v-for="item in shopList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
            <el-form-item label="配送方式">
              <span>{{ sendForm.order.shippingMethod | watchShippingMethod}}</span>
        </el-form-item> 
       
         <!-- <el-form-item label="配送方式"  v-if='sendForm.order.shippingMethod==2'>
          <el-select  filterable placeholder="请选择" v-model="deliveryMethod" @change="selectShop" >
             <el-option label="店家配送" value="1"></el-option>
             <el-option label="骑手配送" value="2"></el-option>
          </el-select>
        </el-form-item>  -->
       
        <!-- <el-form-item label="送货员" style="margin-left: 10px;" v-if="sendForm.order.shippingMethod==2">
          <el-select style="width: 100%" v-model="operatorName" value-key="id" filterable placeholder="请选择"
                     @change="selectSysEmployee">
            <el-option
              v-for="item in sysEmployeeList"
              :key="item.id"
              :label="item.name"

              :value="item">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="发货日期" style="margin-left: 10px;" prop="orderDate">
          <!-- <el-date-picker
            style="width: 140px"
            value-format="yyyy-MM-dd"
            v-model="sendForm.orderDate"
            align="right"
            type="date"
            placeholder="选择日期"
            
          /> -->
       <span> {{sendForm.orderDate }}</span>
        </el-form-item>

      </div>
      <el-form-item label="收货地址" prop="address" style="width: 800px">
        <!-- <el-select style="width: 100%" v-model="sendData.address" value-key="id" filterable placeholder="请选择"
                   @change="changeAddress" disabled>
          <el-option
            v-for="item in receiverForm"
            :key="item.id"
            :label="item.address"
            :value="item">
          </el-option>
          <el-option style="background-color: #f9f9f9;text-align: center;" key="*" label="底部隐藏块"
                     value="*"></el-option>
          <el-option style="background-color: #f9f9f9;text-align: center;position: absolute;bottom:0;width: 100%" key="#" label="--- 新增收货地址 ---"
                     value="#"></el-option>
        </el-select> -->
        {{sendData.address}}
      </el-form-item>
      <el-form-item label="收货人" >
        <div style="display: flex;align-items: flex-end">
          <div style="display: flex; flex-direction: column;">
            <span>{{ sendForm.order.consignee }} {{ sendForm.order.phone }}</span>
          </div>
        </div>
      </el-form-item>
      <!-- <div style="display: flex;">
        <el-form-item label="配送时间" v-show="bomType==1">
          <div style="display: flex; flex-direction: column;">
            <el-select v-model="weekDate" multiple placeholder="请选择" @change="weekClick">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <span>预计送达时间：{{date | dateFormatter}}</span>
          </div>
        </el-form-item>
        <el-form-item label="客户备注" style="margin-left: 50px" v-show="bomType==1">
          <div style="display: flex; flex-direction: row">
            <el-input style="width:210px;" v-model="memberMemo" placeholder="请输入内容"></el-input>
          </div>
        </el-form-item>
      </div> -->
      <!-- <div class="product_header_name">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">商品明细</span>
      </div> -->
      <!-- <el-table
        :data="sendData.itemList"
        border
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="50"
          align="center"
          fixed
        />
        <el-table-column
          prop="name"
          label="姓名"
          width="180"
        />
        <el-table-column
          prop="spec"
          label="规格"
        />
        <el-table-column
          prop="quantity"
          label="订单数量"
        />
        <el-table-column
          prop="availableShippedQuantity"
          label="待发数量"
        />
        <el-table-column
          fixed="right"
          prop="shippedQuantity"
          label="发货数量"
        >
          <template slot-scope="scope">
            <el-input type="number" @input="numberInput($event,scope.$index)" v-model="scope.row.shippedQuantity" />
          </template>
        </el-table-column>
      </el-table> -->
    </el-form>
    <office-dialog ref="officeDialog" @confirm="dialogConfirm" />
    <!-- <el-dialog
      title="新增地址"
      :visible.sync="receiverVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="receiverClose">
      <div style="position: relative;height: 60vh;overflow: auto">
      <memberAdd :memberType="memberType" @memberClick="memberClick"></memberAdd>
        <receiverAdd  @orderReceiver="orderReceiver" pathType="0" :memberId="sendData.memberId"></receiverAdd>
      </div>
    </el-dialog> -->
  </div>
</template>
<script>
  import {receiverLocation} from '@/api/mapLine'
  import {list as addressList} from '@/api/receiver'
import {EventBus} from '@/api/eventBus'
  import receiverAdd from '@/views/receiver/add'
import utils from '../../../utils/utils'
import OfficeDialog from '@/components/OfficeDialog'
import { list as sysEmployeeList } from '@/api/sysEmployee'
import { list as shopList } from '@/api/shop'
import {update as memberupdate} from '@/api/member'
import { shipping, shippingAndAudit ,calculateEstimateDate,updateWeekAndReceiver} from '@/api/order'
import { audit } from '@/api/warehouse'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: {elDragDialog},
  components: {
    OfficeDialog,receiverAdd
  },
  props: ['sendForm','weekType','memberMemo','bomType'],
      filters: {
      watchShippingMethod(val){
        if (val == 0) {
          return '普通快递'
        } else if (val == 1) {
          return '到店提货'
        } else if (val == 2) {
          return '同城配送'
        } else {
          return '待发货'
        }
      },
    },
  data() {
    return {
      deliveryMethod:'',
      shippingMethod:'',
      nowDate:'',
      address:{},
      sendData: {
        memberId: '',
        address: '',
        itemList: [],
        officeId: '',
        operatorId: ''
      },
      options: [{
        value: '1',
        label: '周一'
      }, {
        value: '2',
        label: '周二'
      }, {
        value: '3',
        label: '周三'
      }, {
        value: '4',
        label: '周四'
      }, {
        value: '5',
        label: '周五'
      },{
        value: '6',
        label: '周六'
      },{
        value: '7',
        label: '周七'
      }],
      date:'',
      receiverId:'',
      weekDate:[],
      receiverForm:[],
      receiverVisible:false,
      weekTime: '',
      currentRow:null,
      addressType:false,
      orderDate: '',
      shopId: '',
      shopName: '',
      officeName: '',
      operatorName: '',
      memberName: '',
      sysEmployeeList: [],
      shopList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      sendRules: {
        // shopName: [
        //   { required: true, message: '请选择仓库', trigger: 'blur' },
        // ],
        // orderDate: [
        //   { required: true, message: '请选择日期', trigger: 'blur' },
        // ],
        // shopName: [
        //   { required: true, message: '请选择配送方式', trigger: 'blur' },
        // ],

      }
    }
  },
  created() {
    if (!utils.isNull(this.sendForm)) {
      console.log(this.sendForm)
      this.memberName = this.sendForm.memberName
      this.sendData.address = this.sendForm.order.areaName + this.sendForm.order.address
      this.sendData.itemList = this.sendForm.order.itemList
      this.sendData.shippingMethod = this.sendForm.order.shippingMethod
      this.sendData.memberId = this.sendForm.order.memberId
      this.sendData.officeId = this.sendForm.order.officeId
      this.receiverId=this.sendForm.order.receiverId
      this.shopId=this.sendForm.order.shopId
      this.sendData.operatorId = this.sendForm.order.operatorId
      this.officeName = this.sendForm.officeName
      // this.operatorName = this.sendForm.operatorName
      this.sendData.itemList.forEach(item => { // 初始化发货数量
        item.shippedQuantity = item.availableShippedQuantity
      })

      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1 + ''
      let day = date.getDate() + ''
      this.$set(this.sendForm, 'orderDate', `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`)
      if (!utils.isNull(this.sendForm.order.weekTime) && this.weekType == true) {
        this.weekTime = this.sendForm.order.weekTime
        this.weekDate = this.sendForm.order.weekTime.split("")
        this.calculateEstimateDateClick()
      }
      // this.sendForm.orderDate = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
    }
    // this.loadShop()
    this.loadReceiver()
    this.loadSysEmployee('')
    // if (this.sendForm.order.shippingMethod==2){
    //   this.loadMapLine(this.receiverId)
    // }
    console.log(this.sendData)
  },
  methods: {
    receiverClose() {
      this.receiverVisible = false;
    },
    loadMapLine(query){
      let params=new URLSearchParams()
      params.append('receiverId',query)
      receiverLocation(params).then(res=>{
        this.sendForm.shopName=res.data.shopName
        // this.shopId=res.data.mapLine.shopId
        console.log( this.sendForm.shopName+'------'+this.shopId)
        this.operatorName=res.data.shippingEmployeeName
        this.shippingEmployeeId=res.data.mapLine.shippingEmployeeId
      })
    },
    changeAddress(data){
      var _this=this
      if (data == '#') {
        _this.receiverVisible = true;
        this.sendForm.order.address = ''
      } else {

        _this.receiverId=data.id
        _this.loadMapLine(_this.receiverId)
        _this.sendForm.address = data.address
        _this.sendForm.order.areaName = data.areaName
        _this.sendForm.order.areaId = data.areaId;
        _this.sendForm.order.consignee = data.consignee;
        _this.sendForm.order.phone = data.phone
      }
      console.log(data)
    },
    // 限制最大发货数量跟最小发货数量
    numberInput (value, index) { 
      console.info("value" + value)
      console.info("this.sendData.itemList[index].availableShippedQuantity" + this.sendData.itemList[index].availableShippedQuantity)
      if (value > this.sendData.itemList[index].availableShippedQuantity) {
        console.info("我进判断了")
        this.sendData.itemList[index].shippedQuantity = this.sendData.itemList[index].availableShippedQuantity
        console.info("this.sendData.itemList[index].shippedQuantity" + this.sendData.itemList[index].shippedQuantity)
      }
    },
    orderReceiver(data) {
      var _this = this;
      console.log(data)
      _this.receiverForm.push(data.data)
      _this.receiverId=data.data.id
      _this.sendForm.order.address = data.data.address
      _this.sendForm.address=data.data.address
      _this.sendForm.order.areaName = data.data.areaName
      _this.sendForm.order.areaId = data.data.areaId;
      _this.sendForm.order.consignee = data.data.consignee;
      _this.sendForm.order.phone = data.data.phone;
      _this.receiverClose()
    },
    chooseClick() {
      var _this = this
      if (_this.receiverId == '') {
        _this.$message({
          message: '请选择地址',
          offset: 120,
          center: true
        })
        return
      }
      const params = new URLSearchParams()
      params.append('orderId', _this.form.id)
      params.append('receiverId', _this.receiverId)
      updateWeekAndReceiver(params).then(res => {
        console.log(res)
        _this.$message({
          message: '修改成功',
          offset: 120,
          center: true
        })
        _this.addressType = false
        _this.receiverId = ''
        _this.$emit('findClick')
      }).catch(err => {
        console.log(err)
      })
    },
    //  销售公司
    dialogShow() {
      console.log('点击了')
      this.$refs.officeDialog.show()
    },
    handleCurrentChange(val) {
      console.log(val)
      this.currentRow = val;
      this.receiverId = val.id
    },
    //  修改地址
    addressClose() {
      var _this = this
      _this.addressType = false
      this.receiverId = ''
    },
    dialogConfirm(val) {
      this.sendData.officeId = val.id
      this.officeName = val.name
    },
    selectShop(data) {
      console.log(data);
      // this.shopId = data
      this.deliveryMethod=data
    },
    addressClick() {
      var _this = this
      _this.loadReceiver()
      _this.addressType = true
    },
    loadReceiver() {
      var _this = this
      const params = new URLSearchParams()
      params.append('memberId',  this.sendData.memberId)
      addressList(params).then(res => {

        _this.receiverForm = res.data.data
        console.log(  _this.receiverForm )
      }).catch(err => {
        console.log(err)
      })
    },
    selectSysEmployee(data) {
      this.shippingEmployeeId = data.id
      this.operatorName=data.name
    },
    //  业务员
    loadSysEmployee(query) {
      var _this = this
      const params = new URLSearchParams()
      params.append('name',query)
      params.append('pageSize',1000)
      sysEmployeeList(params).then(response => {

        _this.sysEmployeeList = response.data.data
      }).catch(error => {
        console.log('error!!')
      })
    },
    // 仓库
    // loadShop() {
    //   var _this = this
    //   const params = new URLSearchParams()
    //   shopList(params).then(response => {
    //     console.log(response)
    //     _this.shopList = response.data.data
    //   }).catch(error => {
    //     console.log('error!!')
    //   })
    // },
    delivery() {
      var adopt = 0 // 用于判断发货量是否小于0
      this.sendData.itemList.forEach(item => {
        console.info("item"+JSON.stringify(item))
        if (item.shippedQuantity > 0) {
          adopt = adopt + item.shippedQuantity
        }
      })
      this.$refs.sendRef.validate((valid) => {
        if (adopt==0) {
          return this.$message({message: '请输入发货数量',type: 'warning'})
        }
        if (valid) {
          var _this = this
          const params = new URLSearchParams()
          params.append('shopId', _this.shopId)

          // if (_this.shippingEmployeeId!=undefined){

          //   params.append('shippingEmployeeId',_this.shippingEmployeeId)
          // }
          if (_this.receiverId!=undefined){
            params.append('receiverId',_this.receiverId)
          }
          params.append('orderDate', _this.sendForm.orderDate)
          params.append('weekTime',_this.weekTime)
          params.append('shippingMethod',_this.sendData.shippingMethod)
          params.append('deliveryMethod',_this.deliveryMethod)

          shipping(_this.sendForm.order.id, params, _this.sendData.itemList).then(response => {
            console.log(response)
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            })
            _this.$emit('findClick')
            _this.$emit('sendClose')
            EventBus.$emit('order-view', response.data)
            if (this.weekType==true){
              _this.memberClick()
            }

          }).catch(error => {
            console.log('error!!')
          })
        }
      })
    },
    // aDeliveryClick() {
    //    // 用于判断发货量是否小于0
    //   var adopt = 0
    //   this.sendData.itemList.forEach(item => {
    //     if (item.shippedQuantity > 0) {
    //       adopt = adopt + item.shippedQuantity
    //     }
    //   })
    //   this.$refs.sendRef.validate((valid) => {
    //     if (adopt==0) {
    //       return this.$message({message: '请输入发货数量',type: 'warning'})
    //     }
    //     if (valid) {
    //       var _this = this
    //       const params = new URLSearchParams()
    //       params.append('shopId', _this.shopId)
    //       if (_this.shippingEmployeeId!=undefined){

    //         params.append('shippingEmployeeId',_this.shippingEmployeeId)
    //       }
    //       if (_this.receiverId!=undefined){
    //         params.append('receiverId',_this.receiverId)
    //       }
    //       params.append('orderDate', _this.sendForm.orderDate)
    //       params.append('weekTime',this.weekTime)
    //       params.append('shippingMethod',_this.shippingMethod)
    //       // _this.sendData.itemList.forEach(function(item) {
    //       //   item.shippedQuantity = item.availableShippedQuantity
    //       // })
    //       shippingAndAudit(_this.sendForm.order.id, _this.sendData.itemList, params).then(response => {
    //         console.log(response)
    //         _this.$message({
    //           message: response.content,
    //           offset: 120,
    //           center: true
    //         })
    //         _this.$emit('findClick')
    //         _this.$emit('sendClose')
    //         EventBus.$emit('order-view', response.data)
    //         if (this.weekType==true){
    //           _this.memberClick()
    //         }
    //       }).catch(error => {
    //         console.log('error!!')
    //       })
    //     }
    //   })
    // },
    weekClick(data){

      this.weekTime = data.join('')
      this.calculateEstimateDateClick()
    },
    calculateEstimateDateClick(){
      var _this = this
      console.log(_this.weekTime)
      const params = new URLSearchParams()
      params.append('week', _this.weekTime)
      calculateEstimateDate(params).then(response => {
        console.log(response)
        _this.date = response.data.estimateDate
      }).catch(error => {
        console.log('error!!')
      })
    },
    memberClick() {
      var _this = this

      if (_this.memberMemo!=null){
        var form = {
          id:this.sendForm.order.memberId,
          memo: _this.memberMemo
        }
        memberupdate(form).then(response => {
          this.$message({
            message: 修改成功,
            offset: 120,
            center: true
          })
        }).catch(error => {

        })
      }

    },
  }
}
</script>

<style scoped>
  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
</style>
